package com.definity.toolkit.ui.widget;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseListener;

import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;

import com.definity.toolkit.ui.Body;
import com.definity.toolkit.ui.widget.model.WidgetListModel;
import com.definity.toolkit.ui.widget.renderer.BasicListCellRenderer;

public class List extends JList implements Widget<List> {

	private static final long serialVersionUID = 6888761535397725864L;

	public List() {
		super(new WidgetListModel());
	}
	
	@Override
	public String id() {
		return getName();
	}

	@Override
	public List id(String id) {
		setName(id);
		return this;
	}

	@Override
	public List properties(Body<List> body) {
		body.content(this);
		return this;
	}

	@Override
	public List size(int width, int height) {
		setPreferredSize(new Dimension(width, height));
		return this;
	}

	@Override
	public WidgetListModel getModel() {
		return (WidgetListModel) super.getModel();
	}
	
	public List addElement(Object item) {
		getModel().addElement(item);
		return this;
	}

	public List removeElement(Object item) {
		getModel().removeElement(item);
		return this;
	}
	
	public List addElements(Iterable<?> items) {
		for (Object item : items) {
			addElement(item);
		}
		return this;
	}
	
	public List mode(ListMode mode) {
		switch (mode) {
		case SINGLE_SELECION:
			setSelectedIndex(ListSelectionModel.SINGLE_SELECTION);
			break;
		case MULTIPLE_SELECTION:
			setSelectedIndex(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			break;
		}
		return this;
	}
	
	public List renderer(BasicListCellRenderer renderer) {
		setCellRenderer(renderer);
		return this;
	}
	
	public List select(int index) {
		setSelectedIndex(index);
		return this;
	}

	public List select(Object item) {
		setSelectedValue(item, true);
		return this;
	}
	
	public List listener(ListSelectionListener listener) {
		addListSelectionListener(listener);
		return this;
	}

	public List listener(MouseListener listener) {
		addMouseListener(listener);
		return this;
	}

	public enum ListMode {
		SINGLE_SELECION,
		MULTIPLE_SELECTION;
	}

	@Override
	public Color background() {
		return getBackground();
	}

	@Override
	public List background(Color background) {
		setBackground(background);
		return this;
	}

	@Override
	public Color foreground() {
		return getForeground();
	}

	@Override
	public List foreground(Color foreground) {
		setForeground(foreground);
		return this;
	}

	@Override
	public Font font() {
		return getFont();
	}

	@Override
	public List font(Font font) {
		setFont(font);
		return this;
	}
	
}
